 layui.define(['layer', 'laytpl', 'element'], function(exports) {
  var $ = layui.jquery,
    layer = layui.layer,
    _modName = 'navbar',
    _win = $(window),
    _doc = $(document),
    laytpl = layui.laytpl,
    element = layui.element;

  var navbar = {
    v: '1.0.5',
    config: {
      data: undefined,  
      remote: {
        url: undefined, 
        type: 'GET'
      },
      elem: undefined,
    },
    set: function(options) {
      var that = this;
      that.config.data = undefined;
      $.extend(true, that.config, options);
      return that;
    },
    /**
     * 是否已设置了elem
     */
    hasElem: function() {
      var that = this,
        _config = that.config;
      if (_config.elem === undefined && $(_config.elem)) {
        layui.hint().error('Navbar error:请配置Navbar容器.');
        return false;
      }
      return true;
    },
    /**
     * 获取容器的jq对象
     */
    getElem: function() {
      var _config = this.config;
      return  $(_config.elem);
    },
    /**
     * 绑定特定a标签的点击事件
     */
    bind: function(callback, params) {
      var that = this,
        _config = that.config;
      var defaults = {
        target: undefined,
        showTips: true
      };
      $.extend(true, defaults, params);
      var _target = defaults.target === undefined ? _doc : $(defaults.target);
      // if (!that.hasElem())
      //     return that;
      // var _elem = that.getElem();

      _target.find("a[href!='javascript:;']").each(function() {
        var _that = $(this);
        _that.off('click').on('click', function() {
          var options = _that.data('options');
          var data;
          if (options !== undefined) {
            try {
              data = new Function('return ' + options)();
              data["elem"]=_that;
            } catch (e) {
              layui.hint().error('Navbar 组件a[data-options]配置项存在语法错误：' + options)
            }
          } else {
            data = {
              icon: _that.data('icon'),
              id: _that.data('id'),
              title: _that.data('title'),
              url: _that.data('url'),
              pid:0,
              elem: _that
            };
          }
          typeof callback === 'function' && callback(data);
        });
      }); 
      return that;
    },
    /**
     * 渲染navbar
     */
    render: function(callback) {
      var that = this,
        _config = that.config, //配置
        _remote = _config.remote, //远程参数配置 
        _tpl = [
          '{{# layui.each(d,function(index, item){ }}',
          '{{# var hasChildren = item.children!==undefined && item.children.length>0; }}',
          //默认展开处理
          '{{# if(item.spread){ }}',
          '     <li class="layui-nav-item layui-nav-itemed">',
          '{{# }else{ }}',
          '     <li class="layui-nav-item">',
          '{{# } }}',
          
          '{{# var l1Url = (item.url!==undefined &&item.url!==null&&item.url.length>0)?item.url:"javascript:;"; }}',
          //一级菜单处理 
          '    <a class="nli" href="{{l1Url}}">',    
          '{{#  if (item.icon.indexOf("fa-") !== -1) { }}',
          '       <i class="fa {{item.icon}}" aria-hidden="true"></i>',
          '{{#  } else { }}',
          '        <i class="layui-icon">{{item.icon}}</i>',
          '{{#  } }}',          
          '     <cite>{{item.title}}</cite>',
          '{{# if(hasChildren){ }}',          
          '     <span class="layui-nav-more"></span>',
          '{{#  } }}',  
          '     </a>',

          //二级菜单处理
          '{{# if(hasChildren){ }}',   
          '   <dl class="layui-nav-child">',    
          '{{# var children = item.children; }}', 
          '{{# layui.each(children,function(childIndex, child){ }}',
          '       <dd>',
          '{{# var l2Url = (child.url!==undefined &&child.url!==null&&child.url.length>0)?child.url:"javascript:;"; }}',
        
          '       <a target="pageiframe" href="{{l2Url}}"  data-options="{pid:{{item.id}},url:\'{{child.url}}\',icon:\'{{child.icon}}\',title:\'{{child.title}}\',id:\'{{child.id}}\'}">',
          '{{#    if (child.icon.indexOf("fa-") !== -1) { }}',
          '         <i class="fa {{child.icon}}" aria-hidden="true"></i>',
          '{{#    } else { }}',
          '         <i class="layui-icon">{{child.icon}}</i>',
          '{{#    } }}',
          '       <span>{{child.title}}</span>',
          '       </a>',
          '       </dd>',
          '{{# }); }}',
          '   </dl>', 
          '{{# } }}',

          '</li>',
          '{{# }); }}',
        ], //模板
        _data = [];
      if (!that.hasElem())
        return that;
      var navbarLoadIndex = layer.load(2);
      var _elem = that.getElem();
      //本地数据优先
      if (_config.data !== undefined && _config.data.length > 0) {
        _data = _config.data;
      } else { 
        var options = {
          url: _remote.url,
          type: _remote.type,
          error: function(xhr, status, thrown) {
            layui.hint().error('Navbar error:AJAX请求出错.' + thrown);
            navbarLoadIndex && layer.close(navbarLoadIndex);
          },
          success: function(res) {
            _data = res;
          }
        };
        $.extend(true, options,{
          dataType: 'json'
        });
        $.support.cors = true;
        $.ajax(options);
      }
      var tIndex = setInterval(function() {
        if (_data.length > 0) {
          clearInterval(tIndex);
          //渲染模板
          laytpl(_tpl.join('')).render(_data, function(html) {
            _elem.html(html);
            element.init();
            that.bind(function(data) {
              typeof callback === 'function' && callback(data);
            });
            //关闭等待层
            navbarLoadIndex && layer.close(navbarLoadIndex);
          });
        }
      }, 50);
      return that;
    }
  };
  exports(_modName, navbar);
});